package com.example.shushiyunsst.fragment.main.home.child.icon_sst

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.arch.core.executor.ArchTaskExecutor
import com.alibaba.fastjson.JSON
import com.example.library_common.base.BaseDataBindingFragment
import com.example.library_common.glidmodule.GlideApp
import com.example.library_common.global.AppGlobals
import com.example.library_common.networking.RestClient
import com.example.library_common.utils.OnTextListener
import com.example.library_common.utils.timer.BaseTimerTask
import com.example.library_common.utils.timer.ITimerListener
import com.example.shushiyunsst.R
import com.example.shushiyunsst.databinding.CurrencyTransferSellFragmentBinding
import com.example.shushiyunsst.fragment.getUserBalanceInfo
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.fragment.main.home.child.icon_sst.bean.*
import com.example.shushiyunsst.util.PayingPassWordVerifyPop
import com.example.shushiyunsst.util.push.helper.PushHelper
import com.example.wallet.db.BalanceInfoManager
import com.example.wallet.db.UserInfoManager
import com.example.wallet.utils.Preference
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.interfaces.SimpleCallback
import java.util.*

/**
 * 买出
 * */
class CurrencyTransferSellFragment : BaseDataBindingFragment<CurrencyTransferSellFragmentBinding>(),
    View.OnClickListener, ITimerListener, OnTextListener {

    companion object {
        fun newInstance(txId: String): CurrencyTransferSellFragment {
            val args = Bundle()
            args.putString("txId", txId)
            val fragment = CurrencyTransferSellFragment()
            fragment.arguments = args
            return fragment
        }
    }

    private var txId: String? = ""

    private lateinit var mToolbar: Toolbar

    private var bean: CurrencyTransferBean? = null

    private var mTimerTask: BaseTimerTask? = null

    private var mTimer: Timer? = null

    private var timer = 30

    private val handler: Handler = Handler(Looper.getMainLooper())

    private var sst = AppGlobals.getApplication().getString(R.string.wallet_sst)

    private var cml = AppGlobals.getApplication().getString(R.string.wallet_cml)

    private var cny = AppGlobals.getApplication().getString(R.string.wallet_cny)

    private var inputValue = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        txId = arguments?.getString("txId")
    }

    override fun layoutId(): Int {
        return R.layout.currency_transfer_sell_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mToolbar = view.findViewById(R.id.mToolbar)
//        mToolbar.title = "出售SST"
        mToolbar.setNavigationOnClickListener { onBackPressedSupport() }
        viewBinder.mProgressBar.visibility = View.VISIBLE
        viewBinder.onViewClick = this
        viewBinder.onTextListener = this

        val map = mapOf(
            "txid" to txId
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.queryTokenTxByTxid)
            .success {

                parseQueryTokenTxByTxId(it)
                viewBinder.mProgressBar.visibility = View.GONE
                mToolbar.title = "出售 ${bean?.tokenType?.toUpperCase()}"
            }
            .failure {
                Toast.makeText(_mActivity, "获取商家信息失败", Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
                onBackPressedSupport()
            }
            .build()
            .post()
    }

    private fun parseQueryTokenTxByTxId(it: String?) {
        val obj = JSON.parseObject(it)
        val tokenTx = obj["tokenTx"]?.toString() ?: ""
        bean = JSON.parseObject(tokenTx, CurrencyTransferBean::class.java)
        viewBinder.bean = bean

        presentBalance()

        GlideApp.with(this)
            .load(bean?.userLogo)
            .centerCrop()
            .into(viewBinder.icon)
    }


    @SuppressLint("SetTextI18n")
    private fun presentBalance() {
        when (bean?.tokenType) {
            sst -> {
                viewBinder.mainIcon.visibility = View.VISIBLE
                viewBinder.cancelTv.visibility = View.VISIBLE
                viewBinder.motherIconCml.visibility = View.GONE
                viewBinder.priceUnit.text = "价格\t$cny"
                viewBinder.takeOrder.text = "下单"

                viewBinder.tipTv.visibility= View.VISIBLE
                startTimer()
            }
            cml -> {
                viewBinder.priceUnit.text = "价格\t$sst"
                viewBinder.cancelTv.visibility = View.GONE
                viewBinder.mainIcon.visibility = View.GONE
                viewBinder.motherIconCml.visibility = View.VISIBLE
                viewBinder.tipTv.visibility= View.GONE
                val balanceInfo =
                    BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()?.balanceInfo
                viewBinder.titleTemplate.text = "当前${bean?.tokenType}余额"
                viewBinder.moneyTv.text = "${balanceInfo?.scmlBalance}"
                viewBinder.takeOrder.text = "下单并支付"
            }
        }
    }

    private fun startTimer() {
        if (mTimerTask !== null) return

        mTimer = Timer()

        mTimerTask = BaseTimerTask(this)
        mTimer?.schedule(mTimerTask, 0, 1000)
    }

    private fun stopTimer() {


        if (mTimer != null) {
            mTimer?.cancel()
            mTimer = null
        }

        if (mTimerTask != null) {
            mTimerTask?.cancel()
            mTimerTask = null
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.take_order -> {
//                val mBean = CurrencyTransferIntentBean()
                if (TextUtils.isEmpty(inputValue)) {
                    Toast.makeText(_mActivity, "请输入购买数量", Toast.LENGTH_SHORT).show()
                    return
                }
                val inputValue = inputValue.toDouble()
                val limitMin = bean?.limitMin?.toDouble() ?: 0.0
                val limitMax = bean?.limitMax?.toDouble() ?: 0.0

                if (inputValue in limitMin..limitMax) {
                    when (bean?.tokenType) {
                        sst -> {
//                            showBuyingPop()
                            sellingSSTNow()
                        }
                        cml -> {
                            showSellingPop()
//                            buyingCMLNow()
                        }
                    }
//                    selling()

                } else {
                    Toast.makeText(
                        _mActivity,
                        "交易金额必须在${bean?.limitMin} ~ ${bean?.limitMax}之间",
                        Toast.LENGTH_SHORT
                    ).show()
                }


            }
            R.id.forAll -> {
                val mBean = BalanceInfoManager.mBalanceInfoManager.getBalanceInfoBean()
                viewBinder.inputValue.setText("${mBean?.totalBalance}")

            }
        }
    }

    private fun showSellingPop() {

        val mPop = PayingPassWordVerifyPop(_mActivity)
        XPopup.Builder(_mActivity)
            .setPopupCallback(object : SimpleCallback() {
                override fun onDismiss(popupView: BasePopupView?) {
                    super.onDismiss(popupView)
                    if (mPop.getIsOnVerifyPop()) {
                        if (mPop.getVerifyPop()) {
                            sellingCMLNow()

                        } else {
                            Toast.makeText(_mActivity, "支付密码错误", Toast.LENGTH_SHORT).show()
                        }
                    }
                }
            })
            .asCustom(mPop)
            .show()


    }

    private fun sellingCMLNow() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo

        val map = mapOf(
            "sellNuums" to inputValue,
            "tokenType" to bean?.tokenType,
            "txid" to bean?.txid,
            "uid" to userInfo?.uid
        )
        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.saveCmlTxSellOrder)
            .success {
                saveCmlTxSellOrder(it)
                Toast.makeText(_mActivity, "发送成功", Toast.LENGTH_SHORT).show()
                getUserBalanceInfo(_mActivity)
                onBackPressedSupport()
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()
            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()
            }.build().post()
    }

    @SuppressLint("RestrictedApi")
    private fun saveCmlTxSellOrder(it: String?) {
        Log.d("saveCmlTxSellOrder", "saveCmlTxSellOrder== $it")
        val obj = JSON.parseObject(it)
        val pushMsg = obj["pushMsg"] ?: ""
        val txNo = obj["txNo"].toString()
        val mPushMsgBean = JSON.parseObject(JSON.toJSONString(pushMsg), PushMsgBean::class.java)

        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                val deviceTokens = mPushMsgBean.deviceToken
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                val pushHelper = PushHelper()
                mPushMsgBean.type = FU_KUANG
                mPushMsgBean.orderId = txNo
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("购买${bean?.tokenType}")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("购买${bean?.tokenType}")
                broadcast.setCustomField(JSON.toJSONString(mPushMsgBean))
                broadcast.setTitle("${userInfo?.nickName} 向你购买 $inputValue 个 ${bean?.tokenType}")
                broadcast.setText("${userInfo?.nickName} 向你购买 $inputValue 个 ${bean?.tokenType}")

                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }


        }
    }


    private fun sellingSSTNow() {
        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo


        val map = mapOf(
            "sellNuums" to inputValue,
            "tokenType" to bean?.tokenType,
            "txid" to bean?.txid,
            "uid" to userInfo?.uid
        )

        RestClient.builder()
            .raw(JSON.toJSONString(map))
            .url(R.string.saveTxSellOrder)
            .success {
                parseSaveTxSellOrder(it)
            }
            .failure {
                Toast.makeText(_mActivity, "发送失败", Toast.LENGTH_SHORT).show()

            }.error { _, msg ->
                Toast.makeText(_mActivity, msg, Toast.LENGTH_SHORT).show()

            }
            .build()
            .post()
    }

    private fun parseSaveTxSellOrder(it: String?) {

        val obj = JSON.parseObject(it, SaveTxSellOrderBean::class.java)
        startWithPop(ForLendingFragment.newInstance("${obj.order.toid}"))
        pushMsg(obj)
    }

    @SuppressLint("RestrictedApi")
    private fun pushMsg(obj: SaveTxSellOrderBean) {
        ArchTaskExecutor.getIOThreadExecutor().execute {
            try {
                val deviceTokens = obj.pushMsg.deviceToken
                val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
                val pushHelper = PushHelper()
                obj.pushMsg.type = FU_KUANG
                obj.pushMsg.orderId = obj.order.txNo
                val broadcast = PushHelper.getAndroidBroadcast()
                broadcast.setTitle("SST放款")
                broadcast.setDeviceToken(deviceTokens)
                broadcast.setPlaySound(true)
                broadcast.setTicker("SST放款")
                broadcast.setCustomField(JSON.toJSONString(obj.pushMsg))
                broadcast.setTitle("${userInfo?.nickName} 向你放出 ${obj.order?.totalPrice} 个 SSL")
                broadcast.setText("${userInfo?.nickName} 向你放出 ${obj.order?.totalPrice} 个 SSL")

                pushHelper.sendAndroidBroadcast(broadcast)
            } catch (e: Exception) {
                e.printStackTrace()
            }


        }
    }

    @SuppressLint("SetTextI18n")
    override fun onTimer() {
        handler.post {
            timer--
            viewBinder.cancelTv.text = "${timer}s后自动取消"
            if (timer <= 0) {
                stopTimer()
                onBackPressedSupport()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopTimer()
    }

    @SuppressLint("SetTextI18n")
    override fun afterTextChanged(s: Editable?, viewId: Int) {
        when (viewId) {
            R.id.inputValue -> {
                if (!TextUtils.isEmpty(s.toString())) {
                    inputValue = s.toString()
                    viewBinder.costMoney.text = "$inputValue ${bean?.tokenType}"
                }

            }
        }
    }


}